﻿using System;
using System.Collections.Generic;
using System.Text;
using MarketSimulator.Utils.Attributes;
using jade.core.behaviours;
using jade.lang.acl;
using MarketSimulator.Utils.Communication;

namespace MarketSimulator.Agents.Behaviors
{
    /// <summary>
    /// Transporter Behavior
    /// </summary>
    public class TransporterBehavior : CyclicBehaviour
    {
        public TransporterAttributes Attributes;

        public TransporterBehavior(TransporterAttributes attributes)
            : base(attributes.JadeAgent)
        {
            Attributes = attributes;
        }

        public override void action()
        {
            ACLMessage message = null;
            MessageTemplate pattern = MessageTemplate.MatchConversationId(Messages.CONVERSATION_ASK_TRANSPORT_OFFER);
            message = myAgent.receive(pattern);

            if (message != null)
            {
                string pInfo = GetTransportOffer(message.getContent());
                Attributes.WriteMessage("{0} asked for \"{1}\" transport offer. My offer is {2}.", message.getSender().getLocalName(),
                    message.getContent(), pInfo);

                //Send message and required info
                ACLMessage reply = new ACLMessage();
                reply.addReceiver(message.getSender());
                reply.setConversationId(Messages.CONVERSATION_SAY_TRANSPORT_OFFER);
                reply.setContent(pInfo);
                myAgent.send(reply);
            }
            else
            {
                block();
            }
        }

        #region Private Methods

        /// <summary>
        /// Get Offer for Product
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        private string GetTransportOffer(string productInfo)
        {
            int cityA, cityB, quantity;
            string[] parts = productInfo.Split('|');
            cityA = int.Parse(parts[0]);
            cityB = int.Parse(parts[1]);
            quantity = int.Parse(parts[2]);

            if((Attributes.Route.CityA.Id == cityA && Attributes.Route.CityB.Id == cityB) ||
                (Attributes.Route.CityA.Id == cityB && Attributes.Route.CityB.Id == cityA))
            {
                return (quantity / Attributes.Capacity * Attributes.PricePerTransport).ToString();
            }
            else
            {
                return Messages.NOT_AVAILABLE;
            }
        }

        #endregion
    }
}
